<template>
  <div>
    <el-upload class="upload-view" ref="upload" drag :action="autoUpload ? '#' : url" :accept="fileType" :limit="1"
               :headers="header" :show-file-list="false"
               :on-success="onSuccess" v-if="!listType" :auto-upload="!autoUpload"
               :on-change="uploadChange">
      <el-input v-model="value" class="upload-value"/>
      <slot name="content">
        <div class="column-div upload-content">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传{{fileType}}文件{{fileSize? '，且不超过' + fileSize : ''}}</div>
        </div>
      </slot>
    </el-upload>
    <el-upload :action="url" :accept="fileType" :headers="header" :show-file-list="false"
               :on-success="onSuccess" list-type="fileList" v-else-if="tinymce" :multiple="multiple"
               class="button-upload">
      <el-button size="mini">上传图片</el-button>
    </el-upload>
    <el-upload :action="url" :accept="fileType" :headers="header" :show-file-list="false"
               :on-success="onSuccess" list-type="picture-card" v-else :multiple="multiple">
      <i class="el-icon-plus"></i>
    </el-upload>
  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'

  export default {
    props: {
      value: String,
      listType: Boolean,
      autoUpload: Boolean,
      tinymce: Boolean,
      multiple: Boolean,
      fileType: {
        type: String,
        default: '.jpg,.png'
      },
      fileSize: {
        type: String,
        default: ''
      },
      fileList: {
        type: Array,
        default: () => []
      }
    },
    name: 'index',
    data() {
      return {
        url: process.env.VUE_APP_BASE_API + '/wx/appletFeedback/uploadimg',
        header: { Authorization: 'Bearer ' + getToken() }
      }
    },
    methods: {
      uploadChange(event) {
        if (!this.autoUpload) return
        this.$emit('change', event)
        this.$refs.upload.clearFiles()
      },

      onSuccess(event) {
        console.log('onSuccess', event)
        this.$emit('input', event.data.url)
        this.$emit('change', this.listType ? this.fileList?.concat(event.data.url) || [event.data.url] : event.data)
      }
    }
  }
</script>

<style lang="scss">
  .button-upload {
    .el-upload--picture-card {

    }
    .el-upload, .el-upload-dragger {
      width: initial !important;
      height: initial !important;
    }
  }

  .upload-view {
    width: 100%;
    position: relative;
    .upload-value {
      position: absolute;
      z-index: -1;
      opacity: 0;
    }
    .el-upload, .el-upload-dragger {
      width: 100% !important;
    }
    .upload-content {
      width: 100%;
      height: 100%;
      .el-icon-upload {
        margin: 0;
      }
    }
  }

</style>
